package com.mDigitalHealth.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	private final static String DATABASE_NAME = "digital_health.db";
	private final static int DATABASE_VERSION = 1;

	private final String DAILY_DATA_TABLE = "daily";
	private final String HOUR_DATA_TABLE = "hour";
	private final String USER_INFO_TABLE = "userInfo";

	private final String CREATE_DAILY_DATA_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ DAILY_DATA_TABLE
			+ "(_id INTEGER PRIMARY KEY AUTOINCREMENT, loginName text not null, dayStamp DATE not null, dayStepCountTotal INTEGER not null default 0, "
			+ " dayStepCountHight INTEGER not null default 0, dayStepCountMid INTEGER not null default 0, dayStepCountLow INTEGER not null default 0, "
			+ " stepCountStatus INTEGER default 1, isUpload INTEGER default 0)";
	private final String CREATE_HOUR_DATA_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ HOUR_DATA_TABLE
			+ "( _id INTEGER PRIMARY KEY  AUTOINCREMENT, loginName text not null, hourStamp DATE not null, hourStepCountTotal INTEGER not null default 0, "
			+ " hourStepCountHight INTEGER not null default 0, hourStepCountMid INTEGER not null default 0, hourStepCountLow INTEGER not null default 0, "
			+ " stepCountStatus INTEGER default 1, isUpload INTEGER default 0)";
	private final String CREATE_USER_INOF_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ USER_INFO_TABLE
			+ "( _id INTEGER PRIMARY KEY  AUTOINCREMENT, loginName text not null default 'login',loginPassword text not null default 'password',"
			+ " userName text not null default '姓名', userMobilePhone text,regflag text default 0"
			// + ", userTelePhone text, userGender INTEGER not null default 1,"
			// +
			// " userHeight INTEGER not null default 170, userWeight INTEGER not null default 66, stepLength INTEGER not null default 66, "
			// +
			// " runStepLength INTEGER not null default 70, dayPlanStepCount INTEGER not null default 0, userBirthday text not null default 19810101, "
			// +
			// " userCity text not null default '所在城市', userGroupID INTEGER not null default 0, userInfo text not null default '个人介绍', "
			// +
			// " createTime DATE not null default 1358168416572, loginCount INTEGER not null default 0, lastLoginTime DATE not null, userType INTEGER not null default 0, "
			// +
			// " userPriority INTEGER not null default 1, userURL text default 'http://', memo text not null default '无'"
			+ ")";

	public DatabaseHelper(Context mContext) {
		super(mContext, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub

		db.execSQL(CREATE_DAILY_DATA_TABLE);
		db.execSQL(CREATE_HOUR_DATA_TABLE);
		db.execSQL(CREATE_USER_INOF_TABLE);

		// db.execSQL("insert into "+IPS_TABLE+"(number) values('17951')");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

		autoSetBookstoreDatabase(db);
		onCreate(db);

	}

	private void autoSetBookstoreDatabase(SQLiteDatabase db) {

		db.execSQL("DROP TABLE IF EXISTS " + DAILY_DATA_TABLE);
		db.execSQL("DROP TABLE IF EXISTS " + HOUR_DATA_TABLE);
		db.execSQL("DROP TABLE IF EXISTS " + USER_INFO_TABLE);

	}

	public void delete(DataType bookstoreDataType, int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		try {
			db.beginTransaction();
			db.delete(getTableName(bookstoreDataType), " _id = ? ",
					new String[] { Integer.toString(id) });
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			db.endTransaction();
		} finally {
			db.close();
		}

	}

	public void delete(DataType bookstoreDataType, String whereClause, String[] whereArgs) {
		SQLiteDatabase db = this.getWritableDatabase();
		try {
			db.beginTransaction();
			db.delete(getTableName(bookstoreDataType), whereClause, whereArgs);
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			db.endTransaction();
		} finally {
			db.close();
		}

	}

	public void update(DataType bookstoreDataType, int id, ContentValues values) {
		SQLiteDatabase db = this.getWritableDatabase();
		try {
			db.beginTransaction();
			db.update(getTableName(bookstoreDataType), values, "_id = ? ",
					new String[] { Integer.toString(id) });
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			db.endTransaction();
		} finally {
			// db.close();
		}
	}

	public void update(DataType bookstoreDataType, ContentValues values, String where,
			String[] selectionArgs) {
		SQLiteDatabase db = this.getWritableDatabase();
		try {
			db.beginTransaction();
			db.update(getTableName(bookstoreDataType), values, where, selectionArgs);
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			db.endTransaction();
		} finally {
			db.close();
		}
	}

	public long insert(DataType bookstoreDataType, ContentValues values) {
		long rowId = -1;
		SQLiteDatabase db = this.getWritableDatabase();
		try {
			db.beginTransaction();
			rowId = db.insert(getTableName(bookstoreDataType), null, values);
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			db.endTransaction();
		} finally {
			db.close();
		}
		return rowId;
	}

	public Cursor query(DataType bookstoreDataType, String selection, String[] selectionArgs,
			String groupBy, String having, String orderBy) {
		SQLiteDatabase db = this.getReadableDatabase();
		return db.query(getTableName(bookstoreDataType), null, selection, selectionArgs, groupBy,
				having, orderBy);
	}

	public Cursor query(DataType bookstoreDataType, String whereCase) {
		SQLiteDatabase db = this.getReadableDatabase();
		return db.rawQuery("select * from " + getTableName(bookstoreDataType) + " where "
				+ whereCase, null);

	}

	/**
	 * 
	 * query 方法
	 * <p>
	 * 方法说明:
	 * </p>
	 * 
	 * @param bookstoreDataType
	 * @param columns
	 * @param selection
	 * @param selectionArgs
	 * @param orderBy
	 * @return
	 * @return Cursor
	 * @author zengtao
	 * @date 2011-12-8
	 */
	public Cursor query(DataType bookstoreDataType, String[] columns, String selection,
			String[] selectionArgs, String orderBy) {
		SQLiteDatabase db = this.getReadableDatabase();
		return db.query(getTableName(bookstoreDataType), columns, selection, selectionArgs, null,
				null, orderBy);
		/*try {
			return db.query(getTableName(bookstoreDataType), null, selection, selectionArgs, 
					groupBy, having, orderBy);
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			db.close();
		}
		return null;*/
	}

	/**
	 * 
	 * query 方法
	 * <p>
	 * 方法说明:
	 * </p>
	 * 
	 * @param bookstoreDataType
	 * @param columns
	 * @param selection
	 * @param selectionArgs
	 * @param groupBy
	 * @param orderBy
	 * @param limit
	 * @return
	 * @return Cursor
	 * @author zengtao
	 * @date 2011-12-8
	 */
	public Cursor query(DataType bookstoreDataType, String[] columns, String selection,
			String[] selectionArgs, String groupBy, String orderBy, String limit) {
		SQLiteDatabase db = this.getReadableDatabase();
		return db.query(getTableName(bookstoreDataType), columns, selection, selectionArgs, null,
				null, orderBy, limit);
		/*try {
			return db.query(getTableName(bookstoreDataType), null, selection, selectionArgs, 
					groupBy, having, orderBy);
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			db.close();
		}
		return null;*/
	}

	/**
	 * throuth the BookstoreDataType get the table name
	 * 
	 * @param bookstoreDataType
	 * @return
	 */
	private String getTableName(DataType bookstoreDataType) {
		String retval = null;
		switch (bookstoreDataType) {
		case DAILY_DATA:
			retval = DAILY_DATA_TABLE;
			break;
		case HOUR_DATA:
			retval = HOUR_DATA_TABLE;
			break;
		case USER_INFO:
			retval = USER_INFO_TABLE;
			break;
		default:
			retval = null;
			break;
		}
		return retval;
	}

}
